﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Drawing;

namespace OpenLS.Spreadsheet.Formats.Biff.OfficeArt
{
    internal class OfficeArtBStoreContainer : OfficeArtRecord
    {
        private readonly List<OfficeArtBStoreContainerFileBlock> _rgfb = new List<OfficeArtBStoreContainerFileBlock>();

        public override RecType RecordType
        {
            get { return RecType.OfficeArtBStoreContainer; }
        }

        public OfficeArtBStoreContainer()
        {
            
        }

        public OfficeArtBStoreContainer(IEnumerable<OfficeArtBStoreContainerFileBlock> blocks)
        {
            _rgfb.AddRange(blocks);
        }
        public OfficeArtBStoreContainer(IEnumerable<OfficeArtFBSE> blocks)
        {
            foreach (var item in blocks)
                _rgfb.Add(item);
        }

        protected override void ReadNoHeader(OfficeArtReadContext context)
        {
            Contract.Assert(rhrecType == RecType.OfficeArtBStoreContainer);
            Contract.Assert(rhrecVer == 0xF);
#if DEBUG
            var position = context.BaseStream.Position;
#endif

            _rgfb.Clear();
            for (int i = 0; i < rhrecInstance; i++)
            {
                OfficeArtBStoreContainerFileBlock item = (OfficeArtBStoreContainerFileBlock)OfficeArtRecord.ReadRecord(context);
                _rgfb.Add(item);
            }
#if DEBUG
            var newPosition = context.BaseStream.Position;
            Contract.Assert(newPosition - position == rhrecLen);
#endif

        }

        protected override byte Version
        {
            get { return 0xF; }
        }

        protected override int ByteLength
        {
            get { return Enumerable.Sum(_rgfb, item => item.FullByteLength); }
        }


        protected override void WriteNoHeader(OfficeArtWriteContext context)
        {
            Contract.Assert(rhrecVer == 0xF);
            Contract.Assert(rhrecType == RecType.OfficeArtBStoreContainer);
            foreach (var item in _rgfb)
                item.Write(context);
        }

        protected override void PrepareHeader(ref OfficeArtRecordHeader rh)
        {
            rh.recInstance = (ushort)_rgfb.Count;
        }

        public OfficeArtBStoreContainerFileBlock GetBlip(int blipId)
        {
            return this._rgfb[blipId - 1];
        }
    }
}